import { useCallback, useContext, useEffect, useMemo, useState } from 'react';
import { SearchOutlined, EyeOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { TagSelectNew } from '@/components/TagSelectNew';
import { UploadFormCommon } from '@/components/UploadForm';
import {
  getLoadMapList,
  getTenantID,
  getUserDepName,
  getFileNameByPath,
  getUserDepID,
  renderTableTextNotColor,
  getSelectDataMapList,
  getCompanyID,
  getPosIDs,
  getUserID,
  getUserName,
  getUserShortCode,
  getColorTextLoadMap,
  splitFileUrl,
  downloadTemplate,
  getFileNameNotType,
} from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import moment from 'moment';
import { Form, Input, InputNumber, Select, Slider, Tooltip, TreeSelect, message } from 'antd';
import { AcceptanceManageAPI } from '../common/type';
import MyIcon from '@/components/MyIcon';

const getUpdateConfig = ({ leftSelectName, pageType, record, bothForm, changeAssetType }: AcceptanceManageAPI.AcceptLocationPropsStateType) => {
  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //材料品牌
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //材料品牌
    `${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}`, //材料状态
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //材料状态
  ]);
  /** 资产类型 */
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`], 'name', 'id', true);
  /** 材料品牌 */
  const assetBrand = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`], 'name', 'id', true);
  /** 折旧方法 */
  const averageLifeMethod = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`], 'name', 'id', true);
  /** 材料状态 */
  const assetStatusList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIEL_STATUS}`], 'name', 'id', true);
  /** 来源类型 */
  const assetSourcesType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`], 'name', 'id', true);

  /** 更换表单 */
  const changeFormType = (id: string | number) => {
    if (id === '100124021000' || id === '100124021001' || id === '100124021007' || id === '100124021008') {
      bothForm?.setFieldsValue({
        unitOfMeasurement: 'm²',
      });
    }
    if (id === '100124021002') {
      bothForm?.setFieldsValue({
        unitOfMeasurement: '辆',
      });
    }
    if (id === '100124021003' || id === '100124021004' || id === '100124021005' || id === '100124021006' || id === '100124021009' || id === '100124021010') {
      bothForm?.setFieldsValue({
        unitOfMeasurement: '个',
      });
    }
  };

  useEffect(() => {
    /** 折旧方式 */
    bothForm?.setFieldsValue({
      depreciateType: '100124301000',
    });
    /** 回填表单 */
    if (pageType === 'view' || pageType === 'edit') {
      bothForm?.setFieldsValue({
        ...record,
      });
      // 判断当前是哪种物资类型
      changeFormType(record.assetType);
    } else {
      changeFormType('100124021000');
      bothForm?.setFieldsValue({
        assetType: '100124021000',
        unitOfMeasurement: 'm²',
        assetState: '100124031002',
      });
    }
  }, []);
  /** 表单配置 */
  const [bothConfig, bothMethods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: bothForm,
    name: 'accept-bothForm',
    schemas: [
      {
        key: 'accept-basic',
        title: '基本信息',
        fieldChildren: [
          {
            field: `assetName`,
            label: `材料名称`,
            component: 'Input',
            disabled: pageType === 'view',
            placeholder: '请选择',
            required: true,
          },
          {
            field: `materialCode`,
            label: `材料编码`,
            component: 'Input',
            disabled: pageType === 'view',
            placeholder: '请输入',
            required: true,
          },
          {
            field: `assetStoreName`,
            label: `仓库名称`,
            component: 'InputTextArea',
            disabled: true,
            initialValue: leftSelectName,
            required: true,
            placeholder: '请选择',
            autoSize: { minRows: 1, maxRows: 3 },
          },
          {
            field: `assetType`,
            label: `材料类型`,
            component: 'Render',
            placeholder: '请选择',
            disabled: pageType == 'view' || pageType == 'edit',
            required: true,
            render: (text) => {
              return (
                <TreeSelect
                  loading={mapLoading}
                  disabled={pageType == 'view' || pageType == 'edit'}
                  showArrow={pageType === 'view'}
                  placeholder="请选择"
                  treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`]}
                  showSearch={true}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  treeNodeFilterProp={'name'}
                  onSelect={(_value, node) => {
                    // changeFormType(_value);
                    changeAssetType(_value);
                    bothForm?.setFieldsValue({
                      materialType: _value,
                    });
                  }}
                />
              );
            },
          },
          {
            field: `sourceType`,
            label: `材料来源`,
            component: 'Render',
            disabled: pageType === 'view',
            required: true,
            placeholder: '请选择',
            render: (text) => {
              return (
                <Select
                  loading={mapLoading}
                  options={assetSourcesType}
                  disabled={pageType === 'view'}
                  placeholder="请选择"
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                  }}
                />
              );
            },
          },
          {
            field: `brandType`,
            label: `材料品牌`,
            component: 'Render',
            disabled: pageType === 'view',
            required: true,
            placeholder: '请选择',
            options: assetBrand,
            render: (text) => {
              return (
                <Select
                  loading={mapLoading}
                  options={assetBrand}
                  disabled={pageType === 'view'}
                  placeholder="请选择"
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                  }}
                />
              );
            },
          },
          {
            field: `quantityOrArea`,
            label: `数量/面积`,
            required: true,
            component: 'InputNumber',
            disabled: pageType === 'view',
            placeholder: '请输入',
            min: 0,
            // contentAfter: '份',
            // initialValue: '1',
            pattern: RegularExpression?.twoFloatNumber,
            patternMsg: '请输入整数或保留两位小数',
          },
          {
            field: `unitOfMeasurement`,
            label: `计量单位`,
            disabled: true,
            component: 'Input',
            placeholder: '请输入',
          },
          {
            field: `paramsInfo`,
            label: `材料参数`,
            required: true,
            component: 'Input',
            disabled: pageType === 'view',
            placeholder: '请输入',
          },
          {
            field: `assetValue`,
            label: `参考单价`,
            component: 'InputNumber',
            placeholder: '请输入',
            disabled: pageType === 'view',
            required: true,
            min: 0,
            // contentAfter: '份',
            // initialValue: '1',
            pattern: RegularExpression?.number,
            patternMsg: '请输入整数',
          },
          {
            field: `assetState`,
            label: `材料状态`,
            component: 'Render',
            required: true,
            disabled: true,
            render: (text) => {
              return (
                <Select
                  options={assetStatusList}
                  disabled={true}
                  placeholder="请选择"
                  value={'100124031002'}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                  }}
                  onChange={() => {}}
                />
              );
            },
          },
          {
            field: `scrapRate`,
            label: `残值率`,
            placeholder: '请输入',
            disabled: pageType === 'view',
            min: 0,
            contentAfter: '%',
            pattern: RegularExpression?.twoFloatNumber,
            patternMsg: '请输入整数或保留两位小数',
            component: 'Render',
            render: (text) => {
              if (pageType === 'view') {
                return <span style={{ paddingLeft: 8 }}>{text ? text : '--'}</span>;
              } else {
                return (
                  <Form.Item
                    name="scrapRate"
                    rules={[
                      {
                        pattern: RegularExpression?.twoFloatNumber,
                        message: '请输入整数或保留两位小数',
                      },
                      { type: 'number', min: 0 },
                    ]}
                  >
                    <InputNumber placeholder="请输入" />
                  </Form.Item>
                );
              }
            },
          },
          {
            field: `depreciateType`,
            label: `折旧方式`,
            component: 'Render',
            required: true,
            render: (text) => {
              return (
                <Select
                  options={averageLifeMethod}
                  disabled={true}
                  placeholder="请选择"
                  value={'100124301000'}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                  }}
                />
              );
            },
          },
          {
            field: `assetImage`,
            label: `材料图片`,
            component: 'Input',
            disabled: pageType === 'view',
            required: true,
            placeholder: '请上传',
            render: (text, record) => {
              const fileName = 'assetImage';
              return (
                <>
                  {pageType !== 'view' ? (
                    <UploadFormCommon
                      form={bothForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={true}
                      accept={'.img|.png'}
                      disabledUpload={pageType === 'view'}
                      url={'/purchaseSourceController/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      uploadSuccessCallback={(attachPaths) => {
                        bothForm?.setFieldsValue({
                          assetImage: attachPaths,
                        });
                      }}
                      defaultFiles={text}
                      maxFile={1}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                      delFunc={(delFilePath) => {
                        bothForm?.setFieldsValue({
                          assetImage: '',
                        });
                      }}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                <a
                                  onClick={() => {
                                    message.success('下载中，请稍后...');
                                    downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                  }}
                                >
                                  <MyIcon type="icon-file-text-fill" />
                                  &nbsp;
                                  {getFileNameNotType(e.attachName, 8)}
                                </a>
                              </Tooltip>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
          {
            label: '说明文件',
            field: 'qualityUrl',
            placeholder: '请上传',
            component: 'Render',
            colSpan: 1,
            // required: true,
            render: (text, record) => {
              const fileName = 'qualityUrl';
              return (
                <>
                  {pageType !== 'view' ? (
                    <UploadFormCommon
                      form={bothForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      disabledUpload={pageType === 'view'}
                      // accept={'.doc|.docx'}
                      url={'/purchaseSourceController/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      uploadSuccessCallback={(attachPaths) => {
                        bothForm?.setFieldsValue({
                          qualityUrl: attachPaths,
                        });
                      }}
                      defaultFiles={text}
                      maxFile={1}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                      // isShowUploadBtn={true}
                      delFunc={(delFilePath) => {
                        bothForm?.setFieldsValue({
                          qualityUrl: '',
                        });
                      }}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                <a
                                  onClick={() => {
                                    message.success('下载中，请稍后...');
                                    downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                  }}
                                >
                                  <MyIcon type="icon-file-text-fill" />
                                  &nbsp;
                                  {getFileNameNotType(e.attachName, 8)}
                                </a>
                              </Tooltip>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
          // {
          //   field: `remark`,
          //   label: `备注`,
          //   colSpan: 1,
          //   maxLength: 200,
          //   disabled: pageType === 'view',
          //   showCount: true,
          //   placeholder: '请输入',
          //   autoSize: { minRows: 2, maxRows: 4 },
          //   component: 'Render',
          //   slotRender: (text) => {
          //     if (pageType === 'view') {
          //       return <span style={{ paddingLeft: 8 }}>{text ? text : '--'}</span>;
          //     } else {
          //       return (
          //         <Form.Item
          //           label="备注"
          //           name="remark"
          //           rules={[
          //             {
          //               required: true,
          //               message: '请输入',
          //             },
          //           ]}
          //         >
          //           <Input.TextArea allowClear showCount maxLength={200} placeholder="请输入" autoSize={{ minRows: 2, maxRows: 4 }} />
          //         </Form.Item>
          //       );
          //     }
          //   },
          // },
        ],
      },
    ],
  });

  return {
    bothConfig,
    bothMethods,
  };
};

export { getUpdateConfig };
